import os
import time
import allure

from utils.logger import logger


def ui_exception_record(func):
    def inner(*args, **kwargs):
        self = args[0]
        # 被装饰函数的位置参数
        parameter = args[1:]
        driver = self._driver
        # 高亮标识，为True的话下面就会将元素进行高亮
        style = None
        timestamp = int(time.time())
        image_path = "./images/"
        image = os.path.join(image_path + f'image_{timestamp}.PNG')
        if not os.path.exists(image_path):
            os.makedirs(image_path)
        try:
            # 接收被装饰函数的返回值，即元素信息
            ele = func(*args, **kwargs)
            # 如果被装饰函数执行结果不是None，或者不是list，则只是针对单个元素的find操作，高亮；执行结果是None的话，直接截图
            if ele and type(ele) != list:
                style = True
                # 将元素高亮显示
                self._driver.execute_script("arguments[0].style.border='2px solid red'", ele)
            elif ele and type(ele) == list:
                # 高亮标识，为True的话下面就会执行取消高亮操作
                style = True
                for e in ele:
                    self._driver.execute_script("arguments[0].style.border='2px solid red'", e)
            # 截图
            driver.save_screenshot(image)
            # 取消高亮
            if style and type(ele) != list:
                self._driver.execute_script("arguments[0].style.border=''", ele)
            elif style and type(ele) == list:
                for e in ele:
                    self._driver.execute_script("arguments[0].style.border=''", e)
            with allure.step(f'测试步骤: {parameter}'):
                allure.attach.file(image, name="image", attachment_type=allure.attachment_type.PNG)
            return ele
        except Exception as e:
            logger.warning("执行过程中发生异常")
            logger.warning(f"异常定位的元素信息为：{parameter}")
            # with allure.step(f'异常元素的定位: {parameter}'):
                # 将截图放到报告的数据中
                # allure.attach.file(image, name="image",
                #                    attachment_type=allure.attachment_type.PNG)
            raise e
    return inner